from django.shortcuts import render, redirect
from manage_worker import models
from manage_worker.utills.form import UserModelForm
from manage_worker.utills.pagination import Pagination


def user_list(request):
    '''
    员工列表
    :param request:
    :return:
    '''
    # obj.creat_time.strftime('%Y-%m-%d'),  obj.creat_time取出来不是一个字符串，通过strftime方法转成一个字符串
    # obj.get_gender_display(),   直接取出在model中定义得gender_choices，转换展示
    # obj.depart.title     根据id自动去关联得表中获取哪一行数据得depart队形
    # obj.depart_id     获取数据库中存储得那个字段值
    queryset = models.UserInfo.objects.all()
    page_object = Pagination(request, queryset=queryset, page_size=2)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'user_list.html', context)


def user_add(request):
    '''
    添加用户（原始方式）
    :param request:
    :return:
    '''
    if request.method == 'GET':
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    name = request.POST.get('name')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    ac = request.POST.get('ac')
    time = request.POST.get('time')
    gender = request.POST.get('gender')
    dp = request.POST.get('dp')

    models.UserInfo.objects.create(name=name, password=pwd, age=age, account=ac, gender=gender, depart_id=dp,
                                   creat_time=time)
    return redirect('/user/list/')


def user_model_form_add(request):
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form': form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')

    return render(request, 'user_model_form_add.html', {'form': form})


def user_edit(request, id):
    row_object = models.UserInfo.objects.filter(id=id).first()
    if request.method == 'GET':
        # 根据id去数据库取出数据
        # 要使页面展示默认数据，只需要instance=row_object就可以了
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    # 如果不加instance=row_object就会在表中新增一条数据，加了就会在原先得数据中更改
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存得是用户输入得所有数据，如果想要在用户输入以外增加一些值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list')

    return render(request, 'user_edit.html', {'form': form})


def user_delete(request):
    id = request.GET.get('id')
    models.UserInfo.objects.filter(id=id).delete()

    return redirect('/user/list/')